package com.wsl.HealthChallenge.controllers;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;

import javax.servlet.ServletContext;

import com.google.gdata.client.http.AuthSubUtil;

/**
 * Provides functions to load the private key needed for authentification.
 * 
 * @author mark
 */
public class GoogleHealthAuthUtils {
    /** Authorization constants. */
    private static final String KEY_STORE_FILE = "ghealth_wsl.jks";
    private static final String KEY_ALIAS = "wsl";
    private static final String KEY_STORE_PASS = "wsnh5ever";
    private static final String KEY_PASS = "wsnh4ever";

    /** The cached private key needed to authorize access to Google access. */
    private static PrivateKey cachedPrivateKey = null;

    /**
     * @param servletContext
     * @return
     */
    public static PrivateKey getPrivateKey(ServletContext servletContext) {
        if (cachedPrivateKey == null) {
            cachedPrivateKey = loadPrivateKey(servletContext);
        }
        return cachedPrivateKey;
    }

    /**
     * Loads the private key from disk.
     * @param servletContext
     * @return 
     */
    public static PrivateKey loadPrivateKey(ServletContext servletContext) {
        try {
            try {
                return AuthSubUtil.getPrivateKeyFromKeystore(
                        servletContext.getRealPath(KEY_STORE_FILE), KEY_STORE_PASS, KEY_ALIAS, KEY_PASS);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (GeneralSecurityException e1) {
            e1.printStackTrace();
        }
        return null;
    }
}